package com.iot.platform.mvc.device.controller;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.iot.common.core.exception.ThingModelAbilityException;
import com.iot.common.core.util.R;
import com.iot.common.core.util.UuidUtil;
import com.iot.common.security.annotation.SecurityAuthorization;
import com.iot.platform.api.domain.Device;
import com.iot.platform.api.domain.Product;
import com.iot.platform.api.domain.ThingAbility;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;

@RestController
@RequiredArgsConstructor
@RequestMapping("/device/shadow")
@Api(value = "DeviceShadowController", tags = "设备影子")
public class DeviceShadowController {

	@SecurityAuthorization
	@GetMapping(value = { "/list" }, produces = "application/json; charset=utf-8")
	public R<Map<String,Object>> list(@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
			@RequestParam(name = "productId", required = false, defaultValue = "") String productId,
			@RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
			@RequestParam(name = "limit", required = false, defaultValue = "10") int limit) throws Exception {
		String sqlExceptSelect = " FROM " + Device.TABLE_NAME + " O  WHERE 1=1 ";
		if (!StrKit.isBlank(keywords)) {
			sqlExceptSelect += " AND ( O.NAME LIKE '%" + keywords + "%' OR   O.IDENTIFIER LIKE '%" + keywords + "%' ) ";
		}
		if (!StrKit.isBlank(productId)) {
			sqlExceptSelect += " AND ( O.productId = '" + productId + "') ";
		}

		Page<Device> pages = Device.dao.paginate(cur, limit, "select O.* ", sqlExceptSelect);
		List<Device> list = new LinkedList<Device>();

		for (Device dev : pages.getList()) {
			dev.setProduct(Product.dao.findById(dev.getProductId()));
			list.add(dev);
		}
		
		long online=Db.queryLong("SELECT COUNT(*)   "+sqlExceptSelect+" AND  O.STATUS='1'");
		long unReg=Db.queryLong("SELECT COUNT(*)  "+sqlExceptSelect+" AND  O.STATUS='0' ");
		
		pages.setList(list);
		Map<String,Object> data=new HashMap<String,Object>();
		data.put("pageNumber", pages.getPageNumber());
		data.put("pageSize", pages.getPageSize());
		data.put("totalPage", pages.getTotalPage());
		data.put("totalRow", pages.getTotalRow());
		data.put("list", list);
		data.put("online",online);
		data.put("activate",pages.getTotalRow()-unReg);
		
		return R.ok(data);
	}

	@SecurityAuthorization
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<Device> save(@Valid Device ability) {
		if (ability == null) {
			throw new ThingModelAbilityException("参数必填！");
		}
		if (StrKit.isBlank(ability.getId())) {
			ability.setId(UuidUtil.getUUID());
			if (ability.save()) {
				return R.ok();
			}
		} else {
			if (ability.update()) {
				return R.ok();
			}
		}
		return R.failed();
	}

	@SecurityAuthorization
	@RequestMapping(value = "/getById", method = RequestMethod.GET)
	public R<Device> getById(@RequestParam(name = "deviceId", required = false, defaultValue = "") String deviceId) {

		Device device = Device.dao.findById(deviceId);
		if (device == null) {
			throw new ThingModelAbilityException("功能不存在！");
		}
		device.setProduct(Product.dao.findById(device.getProductId()));
		return R.ok(device);
	}

	@SecurityAuthorization
	@PostMapping(value = { "/deleteById" }, produces = "application/json; charset=utf-8")
	public R<Boolean> deleteById(@RequestParam(name = "id", required = true) String id) throws Exception {
		if (Device.dao.deleteById(id)) {
			return R.ok(true);
		} else {
			return R.failed(false);
		}
	}
	
	/**
	 * 设备运行状态
	 * @param deviceId
	 */
	@SecurityAuthorization
	@GetMapping(value = { "/getRunStatus" }, produces = "application/json; charset=utf-8")
	public R<List<ThingAbility>> getRunStatus(@RequestParam(name = "deviceId", required = true, defaultValue = "") String deviceId,
			@RequestParam(name = "moduleId", required = false, defaultValue = "") String moduleId,
			@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords) {
		Device device=Device.dao.findById(deviceId);
		if(device==null) {
			return R.failed("设备不存在，或参数错误！");
		}
		String _sqlSelect = " SELECT * FROM " + ThingAbility.TABLE_NAME + " O  WHERE o.PRODUCT_ID='"+device.getProductId()+"' AND O.ABILITY_TYPE='0'  ";
		if(!StrKit.isBlank(moduleId)) {
			_sqlSelect+=" AND O.MODULE_ID='"+moduleId+"' ";
		}
		
		if (!StrKit.isBlank(keywords)) {
			_sqlSelect += " AND ( O.NAME LIKE '%" + keywords + "%' OR   O.IDENTIFIER LIKE '%" + keywords + "%' ) ";
		}
		List<ThingAbility> abilities=ThingAbility.dao.find(_sqlSelect);
		return R.ok(abilities);
	}
	
	/**
	 * 设备事件
	 * @param deviceId
	 */
	@SecurityAuthorization
	@GetMapping(value = { "/getEvents" }, produces = "application/json; charset=utf-8")
	public R<List<ThingAbility>> getEvents(@RequestParam(name = "deviceId", required = true, defaultValue = "") String deviceId,
			@RequestParam(name = "moduleId", required = false, defaultValue = "") String moduleId,
			@RequestParam(name = "eventId", required = false, defaultValue = "") String eventId,
			@RequestParam(name = "eventType", required = false, defaultValue = "") String eventType,
			@RequestParam(name = "startEventTime", required = false, defaultValue = "") String startEventTime,
			@RequestParam(name = "stopEventTime", required = false, defaultValue = "") String stopEventTime,
			@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords) {
		
		
		Device device=Device.dao.findById(deviceId);
		if(device==null) {
			return R.failed("设备不存在，或参数错误！");
		}
		String _sqlSelect = " SELECT * FROM " + ThingAbility.TABLE_NAME + " O  WHERE o.PRODUCT_ID='"+device.getProductId()+"' AND O.ABILITY_TYPE='2'  ";
		if(!StrKit.isBlank(moduleId)) {
			_sqlSelect+=" AND O.MODULE_ID='"+moduleId+"' ";
		}
		System.out.println(stopEventTime+"-------"+stopEventTime);
		List<ThingAbility> abilities=ThingAbility.dao.find(_sqlSelect);
		return R.ok(abilities);
	}
	
	/**
	 * 设备服务
	 * @param deviceId
	 */
	@SecurityAuthorization
	@GetMapping(value = { "/getServices" }, produces = "application/json; charset=utf-8")
	public R<List<ThingAbility>> getServices(@RequestParam(name = "deviceId", required = true, defaultValue = "") String deviceId,
			@RequestParam(name = "moduleId", required = false, defaultValue = "") String moduleId) {
		Device device=Device.dao.findById(deviceId);
		if(device==null) {
			return R.failed("设备不存在，或参数错误！");
		}
		String _sqlSelect = " SELECT * FROM " + ThingAbility.TABLE_NAME + " O  WHERE o.PRODUCT_ID='"+device.getProductId()+"' AND O.ABILITY_TYPE='1'  ";
		if(!StrKit.isBlank(moduleId)) {
			_sqlSelect+=" AND O.MODULE_ID='"+moduleId+"' ";
		}
		List<ThingAbility> abilities=ThingAbility.dao.find(_sqlSelect);
		return R.ok(abilities);
	}
	

}
